package com.bcu.cn.onlineexamsystem.studentmanage.service.impl;

import com.bcu.cn.onlineexamsystem.studentmanage.service.DeepSeekService;
import com.bcu.cn.onlineexamsystem.studentmanage.service.ScoreAnalysisService;
import com.bcu.cn.onlineexamsystem.studentmanage.util.DeepSeekRequest;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class DeepSeekServiceImpl implements DeepSeekService {

    private final WebClient webClient;
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final ScoreAnalysisService scoreAnalysisService;

    public DeepSeekServiceImpl(ScoreAnalysisService scoreAnalysisService) {
        this.scoreAnalysisService = scoreAnalysisService;
        this.webClient = WebClient.builder()
                .baseUrl("https://api.deepseek.com/v1/chat/completions")
                .defaultHeader("Authorization", "Bearer sk-2ff0b4382658401e811d9b143e0b2130")
                .build();
    }

    @Override
    public Flux<String> callDeepSeekStream(String userId, String userMessage) {
        // 获取学生最近考试成绩数据
        List<Map<String, Object>> exams = scoreAnalysisService.getRecentExamRecords(userId, 10);
        StringBuilder sb = new StringBuilder();
        sb.append("你是一名善于分析学生成绩并给出学习建议的学习顾问。以下是学生最近的考试成绩数据：\n");
        for (Map<String, Object> exam : exams) {
            sb.append("考试：").append(exam.get("exam_name")).append(", 课程：").append(exam.get("course_name"))
              .append(", 得分：").append(exam.get("score")).append("/ ").append(exam.get("total_score"))
              .append(", 时间：").append(exam.get("submit_time")).append("\n");
        }
        sb.append(userMessage);

        List<DeepSeekRequest.Message> messages = new ArrayList<>();
        messages.add(new DeepSeekRequest.Message("system", "你是一名善于分析学生成绩并给出学习建议的学习顾问。"));
        messages.add(new DeepSeekRequest.Message("user", sb.toString()));

        DeepSeekRequest request = new DeepSeekRequest();
        request.setModel("deepseek-chat");
        request.setMessages(messages);
        request.setStream(true);

        return webClient.post()
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(request)
                .accept(MediaType.TEXT_EVENT_STREAM)
                .retrieve()
                .bodyToFlux(String.class)
                .flatMap(chunk -> {
                    if ("[DONE]".equals(chunk.trim())) {
                        return Flux.empty();
                    }
                    try {
                        JsonNode rootNode = objectMapper.readTree(chunk);
                        JsonNode choicesNode = rootNode.path("choices");
                        if (choicesNode.isArray() && !choicesNode.isEmpty()) {
                            JsonNode deltaNode = choicesNode.get(0).path("delta");
                            String content = deltaNode.path("content").asText("");
                            if (!content.isEmpty()) {
                                return Flux.just(content);
                            }
                        }
                    } catch (Exception e) {
                        return Flux.empty();
                    }
                    return Flux.empty();
                });
    }
} 